package com.storeroompda.ui.basesync;

import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.util.Log;

import com.storeroompda.App;
import com.storeroompda.base.model.BaseModel;
import com.storeroompda.bean.CodeFile;
import com.storeroompda.entity.BillCodeControl;
import com.storeroompda.entity.CodeInfo;
import com.storeroompda.entity.DealerInfo;
import com.storeroompda.entity.ProductInfo;
import com.storeroompda.tool.FileControl;
import com.storeroompda.tool.MathControl;
import com.storeroompda.utils.Utils;
import com.vilyever.socketclient.SocketClient;
import com.vilyever.socketclient.helper.SocketClientDelegate;
import com.vilyever.socketclient.helper.SocketResponsePacket;
import com.vilyever.socketclient.util.CharsetUtil;

import java.nio.charset.Charset;
import java.util.List;

public class BaseSyncModelImpl extends BaseModel implements BaseSyncModel {
    private String tag = "BaseSyncModelImpl";
    private String msg = "";
    private String msg2 = "";
    private String msg3 = "";
    SocketClient socketClient;
    CallBack mlistener;
    byte[] bytest;
    byte[] bytesc;
    boolean flag = false;
    List<CodeFile> listcf;
    int index = 0;

    public void postHandle(final CallBack listener, final int n) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                switch (n) {
                    case -1:
                        listener.onFail(msg);
                        break;
                    case 0:
                        listener.onShow(msg);
                        break;
                    case 1:
                        listener.onbasesync(msg);
                        socketClient.sendString("01");
                        break;
                    case 2:
                        listener.onbasesync(msg2);
                    case 3:
                        listener.onbasesync(msg3);
                        break;
                    default:
                        break;
                }
            }
        });
    }

    @Override
    public void config(final String address, final String port, final CallBack listener) {
        try {
            this.mlistener = listener;
            socketClient = new SocketClient();
            socketClient.getAddress().setRemoteIP(address);
            socketClient.getAddress().setRemotePort(Integer.parseInt(port));
            socketClient.getAddress().setConnectionTimeout(10 * 1000);
            socketClient.setCharsetName(CharsetUtil.UTF_8);
            socketClient.registerSocketClientDelegate(new SocketClientDelegate() {
                @Override
                public void onConnected(SocketClient client) {
                    Log.e(tag, "onConnected");
                    App.sEditor.putString(Utils.addresskey, address);
                    App.sEditor.putString(Utils.portkey, port);
                    App.sEditor.commit();
                    msg = "连接成功";
                    postHandle(listener, 0);
                }

                @Override
                public void onDisconnected(SocketClient client) {
                    Log.e(tag, "onDisconnected");
                    App.sEditor.putString(Utils.addresskey, "");
                    App.sEditor.putString(Utils.portkey, "");
                    App.sEditor.commit();
                    msg = Utils.netConnectionError;
                    postHandle(listener, -1);
                }

                @Override
                public void onResponse(final SocketClient client, @NonNull SocketResponsePacket responsePacket) {
                    Log.e(tag, responsePacket.getMessage());
                    if (responsePacket.getData().length == 20) {
                        index++;
                        if (listcf!=null && listcf.size() == index) {
//                            BillCodeControl.deleteBillAll();
//                            List<CodeInfo> listc = BillCodeControl.SearchCodeList();
//                            if (listc == null || listc.size() <= 1200) {
//                            }
//                            else {
//                                List<CodeInfo> listd = listc.subList(0, listc.size() - 1200);
//                                BillCodeControl.deleteCodeList(listd);
//                            }
                            msg = "同步完成"+index+"文件";
                            index=0;
                            listcf=null;
                            postHandle(listener, 0);
                        } else {
                            baseupCall(listcf.get(index));
                        }
                    } else if (responsePacket.getData().length == 122) {
                        flag = true;
                        bytest = responsePacket.getData();
                    } else if (flag) {
                        flag = false;
                        bytesc = responsePacket.getData();
                        basedownCall(MathControl.addBytes(bytest, bytesc));
                    } else {
                        basedownCall(responsePacket.getData());
                    }
                }
            });
            socketClient.connect();
        } catch (Exception e) {
            e.printStackTrace();
            msg = Utils.exceptionError;
            postHandle(listener, -1);
        }
    }

    @Override
    public void basedown(final CallBack listener) { //先获取产品 再获取经销商
        if (socketClient == null || socketClient.getState() != SocketClient.State.Connected) {
            msg = Utils.netConnectionError;
            postHandle(listener, -1);
            return;
        } else {
            flag = false;
            socketClient.sendString("00");
        }
    }

    @Override
    public void baseup(final CallBack listener) {
        if (socketClient == null || socketClient.getState() != SocketClient.State.Connected) {
            msg = Utils.netConnectionError;
            postHandle(listener, -1);
            return;
        } else {
            try {
                listcf = FileControl.analyzeList(BillCodeControl.searchCodeAll(), BillCodeControl.searchBillAll());
                if (listcf == null || listcf.size() == 0) {
                    msg = Utils.nodata;
                    postHandle(listener, 0);
                    return;
                }
                baseupCall(listcf.get(index));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void disconnect(CallBack listener) {
        socketClient = null;
    }

    private void basedownCall(byte[] bytes) {
        try {
            byte[] byte1 = MathControl.subByte(bytes, 0, 2);
            String str1, str2, str3;
            int len = 0;
            str1 = new String(byte1, "utf-8");
            if (str1.equals("00")) {
                byte[] byte2 = MathControl.subByte(bytes, 2, 100);
                byte[] byte3 = MathControl.subByte(bytes, 102, 20);
                for (int i = 0; i < byte2.length; i++) {
                    if (byte2[i] == 0) {
                        byte[] byte2temp = MathControl.subByte(byte2, 0, i);
                        str2 = new String(byte2temp, "utf-8");
                        Log.e(tag, "str2:" + str2);
                        break;
                    }
                }
                for (int i = 0; i < byte3.length; i++) {
                    if (byte3[i] == 0) {
                        byte[] byte3temp = MathControl.subByte(byte3, 0, i);
                        str3 = new String(byte3temp, "utf-8");
                        Log.e(tag, "str3:" + str3);
                        len = Integer.parseInt(str3);
                        break;
                    }
                }
                Log.e(tag, "len0:" + bytes.length);
                byte[] byte4 = MathControl.subByte(bytes, 122, len);
                String str4 = new String(byte4, "utf-8");
                Log.e(tag, "str4:" + str4);
                String[] strs = str4.split("\n");
                if (strs.length > 0) {
                    BillCodeControl.deleteP();
                    for (int i = 0; i < strs.length; i++) {
                        String[] strss = strs[i].split(",");
                        ProductInfo pi = new ProductInfo(null, strss[0], strss[1].replace("\n", "").replace("\r", ""), "", "", "");
                        BillCodeControl.insertP(pi);
                    }
                    msg = "产品同步" + strs.length + "条";
                    postHandle(mlistener, 1);
                }
            } else if (str1.equals("01")) {
                byte[] byte2 = MathControl.subByte(bytes, 2, 100);
                byte[] byte3 = MathControl.subByte(bytes, 102, 20);
                for (int i = 0; i < byte2.length; i++) {
                    if (byte2[i] == 0) {
                        byte[] byte2temp = MathControl.subByte(byte2, 0, i);
                        str2 = new String(byte2temp, "utf-8");
                        Log.e(tag, "str2:" + str2);
                        break;
                    }
                }
                for (int i = 0; i < byte3.length; i++) {
                    if (byte3[i] == 0) {
                        byte[] byte3temp = MathControl.subByte(byte3, 0, i);
                        str3 = new String(byte3temp, "utf-8");
                        Log.e(tag, "str3:" + str3);
                        len = Integer.parseInt(str3);
                        break;
                    }
                }
                Log.e(tag, "len1:" + bytes.length);
                byte[] byte4 = MathControl.subByte(bytes, 122, len);
                String str4 = new String(byte4, "utf-8");
                Log.e(tag, "str4:" + str4);
                String[] strs = str4.split("\n");
                if (strs.length > 0) {
                    BillCodeControl.deleteD();
                    for (int i = 0; i < strs.length; i++) {
                        String[] strss = strs[i].split(",");
                        DealerInfo di = new DealerInfo(null, strss[0], strss[1].replace("\n", "").replace("\r", ""), "", "", "");
                        BillCodeControl.insertD(di);
                    }
                    msg2 = " 经销商同步" + strs.length + "条";
                    postHandle(mlistener, 2);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
//            msg="";
//            postHandle(mlistener, -1);
        }
    }

    private void baseupCall(CodeFile codeFile) {
        byte[] byte1 = "02".getBytes();

        byte[] byte2 = new byte[100];
        for (int i = 0; i < byte2.length; i++) {
            byte2[i] = '\0';
        }
        String temp = codeFile.getType() + "_" + codeFile.getName() + "_" + codeFile.getDate() + ".txt";
        byte[] byte2temp = temp.getBytes();
        byte2 = MathControl.initByte(byte2, byte2temp);

        byte[] byte3 = new byte[20];
        for (int i = 0; i < byte3.length; i++) {
            byte3[i] = '\0';
        }
        byte[] byte3temp = (codeFile.getContext().getBytes().length + "").getBytes();
        byte3 = MathControl.initByte(byte3, byte3temp);

        byte[] byte4 = codeFile.getContext().getBytes();

        byte[] byte5 = MathControl.addBytes(MathControl.addBytes(byte1, byte2), MathControl.addBytes(byte3, byte4));
        socketClient.sendData(byte5);
    }

}

